/**   
* @Package com.app.open.common.grid 
*/
package com.wlyy.bcwlw.common.grid;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.rework.joss.persistence.convention.utils.ConventionUtils;

/**
 * @ClassName. GridUtils
 * @Description. bsgrid工具
 * @author zhangyang
 * @date 2015年7月24日 下午4:13:50
 * @version V1.0
 */
public class GridUtils {

	// 页面的最大行数
	public static final String PAGE_MAX_PAGE_ITEMS = "pageSize";
	public static final int DEFAULT_PAG_MAX_PAGE_ITEMS = 10;
	
	// 当前页码
	public static final String JSON_KEY_CUR_PAGE = "curPage";
	// 记录总数
	public static final String JSON_KEY_TOTAL_RECORDS = "totalRows";
	// 记录
	public static final String JSON_KEY_RECORD = "data";
	//自定义数据
	public static final String JSON_KEY_USERDATA = "userdata";
	//排序字段
	public static final String PAGE_SORT_NAME="sortName";
	//排序顺序
	public static final String PAGE_SORT_ORDER="sortOrder";
	
	public static final String JSON_KEY_SUCCESS="success";
	
	
	/**
	 * 当前页码
	 * @param request
	 * @return
	 */
	public static int getPageNum(HttpServletRequest request) {
		String page = request.getParameter(JSON_KEY_CUR_PAGE);
		return NumberUtils.isNumber(page) ? Integer.parseInt(page) : 1;
	}
	
	/**
	 * 每页显示记录数
	 * @param request
	 * @return
	 */
	public static int getInternal(HttpServletRequest request) {
		String page = request.getParameter(PAGE_MAX_PAGE_ITEMS);
		return NumberUtils.isNumber(page) ? Integer.parseInt(page) : DEFAULT_PAG_MAX_PAGE_ITEMS;
	}
	
	/**
	 * 当前排序字段
	 * @param request
	 * @return
	 */
	public static String getSortName(HttpServletRequest request){
		return request.getParameter(PAGE_SORT_NAME);
	}
	
	/**
	 * 当前排序类型
	 * @param request
	 * @return
	 */
	public static String getSortOrder(HttpServletRequest request){
		return request.getParameter(PAGE_SORT_ORDER);
	}
	
	public static int getTotalPages(int records, int limit) {
		if(records <= 0) {
			return 0;
		}
		int totalPages = 0;
		totalPages = records / Math.max(limit, 1);
		totalPages = records % Math.max(limit, 1) == 0 ? totalPages : totalPages + 1;
		return totalPages;
	}
	
	
	/**
	 * 为jqGrid构造json格式的数据
	 * @param limit 每页显示记录数
	 * @param page 页码
	 * @param records 总记录数
	 * @param rows 数据
	 * @return
	 */
	public static String constructJsonData4Grid(int limit, int page, int records, List rows,Map userData) {
		int totalPages = getTotalPages(records, limit);
		if (page > totalPages) {
			page = totalPages;
		}
		String json = JSON.toJSONString(ConventionUtils.toMap(
				JSON_KEY_SUCCESS,true,
				JSON_KEY_CUR_PAGE, page, 
				JSON_KEY_TOTAL_RECORDS, records, 
				JSON_KEY_RECORD, rows,
				JSON_KEY_USERDATA, userData)).toString();
		return json;
	}
}
